var apiHost = wx.getStorageSync('apiHost');   //调用接口请求地址
var yunId = wx.getStorageSync('yunId');                //云id
var openId = wx.getStorageSync('openId');              //openId
var deliveryTimeType_sd = "0";                          //时段配送
var deliveryTimeType_ksd = "1";                         //快速达
var pages = getCurrentPages();                          //调用小程序的
var currPage = pages[pages.length - 1];                 //当前页面
var prevPage = pages[pages.length - 2];                 //上一个页面
var nowSendType = "";//当前配送方式

Page({

  deliveryTimeList: [],      //配送时间列表list

  data: {
    items: [],
    multiArray: [],         //配送时段数组
    startTime: [],         //开始时间
    endTime: [],           //结束时间
    deliverTime: [],         //营业时间
    showModal: false,       //提示框是否显示
    showQueModal: false,    //确认框
    hiddenLoading: true,    //loading
    isNone: true,          //显示隐藏判断
    toDoor: "关闭",         //打开关闭
    msg: "",               //提示文字
    currentTab: 0,
    shop_radio: [
      { name: '0', value: '时段配送' },
      { name: '1', value: '快速达' },
    ],
    senfTypeAlert: false

  },

  onLoad: function (options) {
    //页面加载loading
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    var deliveryTimeType = options.deliveryTimeType;   //获取页面传来的参数
    console.log(deliveryTimeType)

    var current = "";

    //判断是“时段配送”还是“时速达”
    if (deliveryTimeType == "0") {
      current = "0";
      that.deliveryTimeList1();   //时段配送基本信息
    } else if (deliveryTimeType == "1") {
      current = "1";
      that.quickInfo();           //时速达送基本信息
    }

    //编辑页面切换  是否显示
    isNone: (options.showView == "true" ? true : false)

    //初始化开始见 24小时制
    for (var i = 0; i < 24; i++) {
      if (i < 10) {
        that.data.startTime.push("0" + i + ":00")
      } else {
        that.data.startTime.push(i + ":00")
      }
    }
    //初始化结束时间24小时制
    for (var i = 0; i < 24; i++) {
      if (i < 10) {
        that.data.endTime.push("0" + i + ":00")
      } else {
        that.data.endTime.push(i + ":00")
      }
    }

    //初始化配送时限 1~5
    for (var i = 1; i < 6; i++) {
      that.data.deliverTime.push(i)
    }

    //初始化picker
    that.data.multiArray.push(that.data.startTime);
    that.data.multiArray.push(that.data.endTime);

    that.setData({
      items: that.data.items,
      multiArray: that.data.multiArray,
      deliverTime: that.data.deliverTime,
      currentTab: current
    });
    /**
     * 获取系统信息
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          heightaa: wx.getSystemInfoSync().windowHeight - wx.getSystemInfoSync().screenWidth / 750 * 180
        });
      }
    });


    that.deliveryTimeList1();   //初始化配送时段

    //创建节点选择器;
    //
    var query = wx.createSelectorQuery();
    query.select('#disPsCon').boundingClientRect();
    query.exec(function (res) {
      //取高度
      that.setData({
        ListHeight: res[0].height
      });
    });



  },
  //配送时间列表
  deliveryTimeList1: function () {

    //显示加载动画
    this.setData({
      hiddenLoading: false
    });

    var that = this;
    // 微信请求（点击分类）
    wx.request({
      url: apiHost + "xcx/deliveryTime/list",
      data: {
        openId: openId,
        yunId: yunId,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code=="10000"){
          that.countdeliveryTimeListHeight();
          that.setData({
            deliveryTimeList: res.data.data,
            hiddenLoading: true                 //关闭加载动画
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
    });
  },
  //计算配送时间列表高度
  countdeliveryTimeListHeight: function () {
    var that = this;
    /*获取指定元素高度*/
    var query = wx.createSelectorQuery();
    var psHeardHeight = "";
    var sdpsConHeight = "";
    //获取店铺头部高度
    query.select('#psHeard').boundingClientRect()
    query.exec(function (res) {
      psHeardHeight = res[0].height;
    });

    query.select('#sdps_con').boundingClientRect()
    query.exec(function (res) {
      sdpsConHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            deliveryTimeListHeight: res.windowHeight - psHeardHeight - sdpsConHeight + 30,
            deliveryTimeconHeight: res.windowHeight - psHeardHeight
          });
        }
      });
    });
  },
  //时段 开启，关闭
  switchChange: function (e) {

    var operateTimeOpen = "1";  //开启状态
    var operateTimeColse = "0"; //关闭状态

    var that = this;
    var operateTimeId = e.target.dataset.toggle; //当前时间段id

    // 判断是否打开
    if (e.detail.value) {
      that.operateTimeUpdata(operateTimeId, operateTimeOpen);  //关闭开启配送时段 修改
    } else {
      that.operateTimeUpdata(operateTimeId, operateTimeColse); //关闭开启配送时段 修改
    }
  },
  /**
   * 关闭开启配送时段 修改
   * @param timeId 配送时段Id
   * @param state 0关闭 1开启
   */
  operateTimeUpdata: function (timeId, state) {
    var that = this;
    wx.request({
      url: apiHost + "xcx/deliveryTime/operateTime",
      data: {
        openId: openId,
        timeId: timeId,
        yunId: yunId,
        state: state
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (e) {
        that.deliveryTimeList1();   //初始化配送时段
      }
    });
  },
  //点击添加时段
  bindMultiPickerChange: function (e) {
    var that = this;
    var startTime = this.data.multiArray[0][e.detail.value[0]];
    var endTime = this.data.multiArray[1][e.detail.value[1]];

    that.operateTimeAdd(deliveryTimeType_sd, startTime, endTime, "", ""); //添加配送时段方法
  },
  /**
   * 修改配送时间段方法
   * @param e
   * @constructor
   */
  TimeChange: function (e) {

    var that = this;

    var timeId = e.target.dataset.toggle;
    var startTime = this.data.multiArray[0][e.detail.value[0]];
    var endTime = this.data.multiArray[1][e.detail.value[1]];

    that.operateTimeAdd(deliveryTimeType_sd, startTime, endTime, timeId, ""); //添加配送时段方法
  },
  /**
   *
   * @param startTime
   * @param endTime
   */
  /**
   * 添加配送时段方法
   * @param deliveryTimeType  配送类型 0 时段配送 1快速达
   * @param startTime         开始时间
   * @param endTime           结束时间
   * @param timeId            则代表修改配送时段的的配送区间
   * @param quickTime         送达时限
   */
  operateTimeAdd: function (deliveryTimeType, startTime, endTime, timeId, quickTime) {

    var that = this;

    wx.request({
      url: apiHost + "xcx/deliveryTime/addOrEdit",
      data: {
        openId: openId,
        yunId: yunId,
        startTime: startTime,
        endTime: endTime,
        deliveryTimeTypeId: timeId,
        quickTime: quickTime,
        deliveryTimeType: deliveryTimeType
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.deliveryTimeList1();   //初始化配送时段
          that.quickInfo();           //时速达送基本信息
          that.setData({
            msg: res.data.msg,
            showModal: true,
            onclickCon: "onConfirm"
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }


      }
    });
  },
  //删除配送时段
  operateTimeDel: function (timeId) {
    var that = this;
    wx.request({
      url: apiHost + "xcx/deliveryTime/del",
      data: {
        openId: openId,
        yunId: yunId,
        deliveryTimeId: timeId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (e) {
        that.deliveryTimeList1();   //初始化配送时段
        that.hideQueModal();        //关闭模态框
      }
    });
  },
  //时段配送 编辑按钮
  updataTime: function () {
    var that = this;
    that.setData({
      isNone: (!that.data.isNone)
    })
  },
  //删除事件
  del: function (e) {
    var that = this
    var TimeId = e.target.dataset.toggle;

    that.setData({
      msg: "确定要删除您选择的选项",
      showQueModal: true,
      timeId: TimeId
    });
  },

  //时速达基本信息
  quickInfo: function () {
    var that = this;

    //显示加载动画
    that.setData({
      hiddenLoading: false
    });


    wx.request({
      url: apiHost + "xcx/deliveryTime/quickInfo",
      data: {
        yunId: yunId,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.setData({
            quickInfocon: res.data.data,
            hiddenLoading: true        //隐藏loading
          });
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      }
    });
  },
  //选择器点击确认时间
  quickInfoSelectChange: function (e) {
    var that = this;

    var startEndTime = e.target.dataset.toggle;    //获取页面上开始时间和结束时间的拼接

    var startEndTimeList = startEndTime.split(","); //逗号隔开开始时间和结束时间

    var startTime = startEndTimeList[0];            //店铺开店开始时间
    var endTime = startEndTimeList[1];              //店铺开店结束时间

    var deliverTime = that.data.deliverTime[e.detail.value];    //选择的送达时限

    that.operateTimeAdd(deliveryTimeType_ksd, startTime, endTime, "", deliverTime); //添加配送时段方法
  },
  //选择器点击确认时间
  quickInfoChange: function (e) {

    var that = this;

    var startTime = that.data.multiArray[0][e.detail.value[0]];
    var endTime = that.data.multiArray[1][e.detail.value[1]];

    that.quickInfoUpdata(startTime, endTime)

  },
  //修改时速达信息
  quickInfoUpdata: function (startTime, endTime) {
    var that = this;
    that.operateTimeAdd(deliveryTimeType_ksd, startTime, endTime, "", ""); //添加配送时段方法
    that.quickInfo();
  },

  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  hideQueModal: function () {
    this.setData({
      showQueModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  onQueCancel: function () {
    this.hideQueModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
  },
  onDel: function (e) {
    var that = this;
    var TimeId = e.target.dataset.toggle; //获取当前按钮上的id
    that.operateTimeDel(TimeId);           //删除配送时间段
  },
  /**
   ** 滑动切换tab
   */
  bindChange: function (e) {
    var that = this;

    var current = e.target.dataset.current;

    //如果是时段配送 就加载时段配送
    if (current == "0") {
      that.deliveryTimeList1();   //时段配送基本信息
    } else {
      that.quickInfo();           //时速达送基本信息
    }
    //  重新设置tab 页数
    that.setData({ currentTab: current });
    that.backDeliveryTimeType(current);
  },
  chgCancle: function () {
    var that = this;
    that.setData({
      senfTypeAlert: false
    })
    if (nowSendType == "0"){
      that.setData({
        currentTab: "1"
      })
    }else{
      that.setData({
        currentTab: "0"
      })
    }
  },
  chgSendtype: function () {
    var that = this;
    that.setData({
      senfTypeAlert: false
    })
    console.log("nowSendType");
    console.log(nowSendType);
    //点击确认修改后生效
    if (nowSendType == "0") {
      //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
      that.deliveryTimeList1();   //时段配送基本信息
    } else {
      that.quickInfo();           //时速达送基本信息
    }
    that.backDeliveryTimeType(nowSendType);
  },
  /**
   * 点击tab切换
   */
  swichNav: function (e) {
    var that = this;

    console.log(that.data.currentTab)
    nowSendType = e.target.dataset.current;
    if (that.data.currentTab == nowSendType) {
      return false;
    } else {
      that.setData({
        currentTab: nowSendType,
        senfTypeAlert: true
      })
    }
  },
  //此方法用于文本框输入回调
  backDeliveryTimeType: function (deliveryTimeType) {

    //获取页面栈
    var pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2];
      //关键在这里
      prePage.changeData(deliveryTimeType)
    }
  }
});